package com.shwread.android.qysw.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.netease.nim.demo.session.model.extension.ActivityAttachment;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.team.TeamService;
import com.netease.nimlib.sdk.team.model.Team;
import com.shwread.android.qysw.adapter.SelectAdapter;
import com.shwread.android.qysw.adapter.SelectAdapter.SelectViewHolder;
import com.shwread.android.qysw10000243.R;
import com.shwread.http.util.Logger;

import java.util.ArrayList;
import java.util.List;

import logic.bean.NewInteractionInfo;
import logic.constants.DefaultConsts;
import logic.util.Utils;


/**
 * 群选择界面
 * 
 * @author xuzhijun
 * @date 2015年5月8日上午11:04:35
 */
public class NewInteractionCenterChoseGroupActivity
        extends
        BaseSimpleActivity
        implements
        OnClickListener,
        OnItemClickListener
{
	private Context            mContext;
	//Title
	private TextView           tvTitle;
	private Button             btnBack;
	private Button             btnSubmit;
	
	private ListView           groupListView;
	private SelectAdapter      adapter;
	private List<Team>         list;
	private int                checkNum;     // 记录选中的条目数量 
	private NewInteractionInfo info;
	
	private View               allView;
	private CheckedTextView    ctvAll;
	private LinearLayout       gvtopView;
	
	private Handler            myhHandler = new Handler()
	                                      {
		                                      
		                                      @Override
		                                      public void handleMessage(Message msg) {
			                                      super.handleMessage(msg);
		                                      }
		                                      
	                                      };
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_interaction_center_chose_group_activity);
		mContext = this;
		initData();
		setData();
		initView();
		prepareGroupData();
		initListener();
	}
	
	private void initView() {
		//Title		
		tvTitle = (TextView) findViewById(R.id.common_header_name);
		tvTitle.setText("选择群组");
		btnBack = (Button) findViewById(R.id.common_header_back);
		btnBack.setVisibility(View.VISIBLE);
		btnSubmit = (Button) findViewById(R.id.common_header_publish);
		btnSubmit.setVisibility(View.VISIBLE);
		groupListView = (ListView) findViewById(R.id.new_interaction_center_chose_list);
		
		//		allView = LayoutInflater.from(mContext).inflate(R.layout.select_group_item, groupListView, false);
		gvtopView = (LinearLayout) findViewById(R.id.select_group_top_llay);
		//		ctvAll = (CheckedTextView) findViewById(R.id.item_cb);
		ctvAll = (CheckedTextView) findViewById(R.id.select_groud_item_cb);
		ctvAll.setText("全部");
		
		//		groupListView.addHeaderView(allView);
		groupListView.setAdapter(adapter);
		groupListView.setOnItemClickListener(this);
	}
	
	private void setData() {
		adapter = new SelectAdapter(list, this);
		info = (NewInteractionInfo) getIntent().getSerializableExtra(DefaultConsts.INTERACTIONINFO);
	}
	
	private void initData() {
		list = new ArrayList<Team>();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		
	}
	
	void prepareGroupData() {
		NIMClient.getService(TeamService.class).queryTeamList().setCallback(new RequestCallback<List<Team>>()
		{
			
			@Override
			public void onException(Throwable arg0) {
				Logger.d("onSuccess");
			}
			
			@Override
			public void onFailed(int arg0) {
				Logger.d("onSuccess");
			}
			
			@Override
			public void onSuccess(final List<Team> arg0) {
				Logger.d("onSuccess");
				myhHandler.post(new Runnable()
				{
					
					@Override
					public void run() {
						if (list.size() > 0) list.removeAll(list);
						list.addAll(arg0);
						initAdapterCheckState();
					}
				});
				
			}
			
		});
	}
	
	void initAdapterCheckState() {
		// 遍历list的长度，将SelectAdapter中的map值全部设为true  
		for (int i = 0; i < list.size(); i++)
		{
			SelectAdapter.getIsSelected().put(i, false);
		}
		// 刷新listview和TextView的显示  
		adapter.notifyDataSetChanged();
		gvtopView.setOnClickListener(this);
	}
	
	private void initListener() {
		btnBack.setOnClickListener(this);
		btnSubmit.setOnClickListener(this);
		ctvAll.setOnClickListener(this);
		
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.common_header_back:
				finish();
				break;
			case R.id.common_header_publish:
				sendMsg();
				break;
			case R.id.select_group_top_llay:
			case R.id.select_groud_item_cb:
				updateAllBtn();
				break;
			default:
				break;
		}
	}
	
	private void updateAllBtn() {
		if (ctvAll.isChecked())
		{
			ctvAll.setChecked(false);
			checkNum=0;
			for (int i = 0; i < list.size(); i++)
			{
				SelectAdapter.getIsSelected().put(i, false);
			}
		}
		else
		{
			checkNum=list.size();
			ctvAll.setChecked(true);
			for (int i = 0; i < list.size(); i++)
			{
				SelectAdapter.getIsSelected().put(i, true);
			}
		}
		adapter.notifyDataSetChanged();
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		// 取得ViewHolder对象，这样就省去了通过层层的findViewById去实例化我们需要的cb实例的步骤  
		SelectViewHolder holder = (SelectViewHolder) view.getTag();
		// 改变CheckBox的状态  
		holder.ctv.toggle();
		// 将CheckBox的选中状况记录下来  
		SelectAdapter.getIsSelected().put(position, holder.ctv.isChecked());
		// 调整选定条目  
		if (holder.ctv.isChecked() == true)
		{
			checkNum++;
		}
		else
		{
			checkNum--;
		}
		
		if (checkNum == list.size())
		{
			myhHandler.post(new Runnable()
			{
				
				@Override
				public void run() {
					
					ctvAll.setChecked(true);
				}
			});
		}
		else
		{
			myhHandler.post(new Runnable()
			{
				
				@Override
				public void run() {
					ctvAll.setChecked(false);
				}
			});
			
		}
	}
	
	void sendMsg() {
		if (!SelectAdapter.getIsSelected().containsValue(true))
		{
			Utils.showToast(mContext, "请选择群组");
		}
		else
		{
			
			for (int i = 0; i < SelectAdapter.getIsSelected().size(); i++)
			{
				if (SelectAdapter.getIsSelected().get(i))
				{
					Team team = list.get(i);
					ActivityAttachment attachment = new ActivityAttachment(info);
					IMMessage message = MessageBuilder.createCustomMessage(team.getId(), SessionTypeEnum.Team, attachment);
					NIMClient.getService(MsgService.class).sendMessage(message, false);
				}
			}
			finish();
		}
	}
	
}
